{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "768fe049-2a37-46cc-9cd2-01aba9f269cd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2 的算术平方根= 1.4142135623746899\n",
      "3 的算术平方根= 1.7320508075688772\n",
      "2 的算术平方根= 1.414213562373095\n",
      "3 的算术平方根= 1.7320508075688772\n"
     ]
    }
   ],
   "source": [
    "#求 a 的算术平方根的近似方法\n",
    "def sqrtA( a ):\n",
    "    if a<0:\n",
    "        a = -a\n",
    "    if a==0:\n",
    "        return 0\n",
    "    x1 = 1.0\n",
    "    while True:\n",
    "        x2 = (x1 + a / x1 )/2\n",
    "        if abs(x2-x1)> 1E-6 *( abs(x2)+abs(x1)):\n",
    "            #如果还没有达到计算精度\n",
    "            x1 = x2\n",
    "        else:\n",
    "            break\n",
    "    return x2\n",
    "\n",
    "import math\n",
    "def sqrtA2( a ):\n",
    "    x0 = a;x1 = (x0 + a / x0) / 2\n",
    "    while (abs(x1 - x0) > pow(10, -6)):\n",
    "        x0 = x1; x1 = (x0 + a / x0) / 2\n",
    "    return x1\n",
    "#测试代码\n",
    "a=2\n",
    "print( a,\"的算术平方根=\",sqrtA( a ))\n",
    "a=3\n",
    "print( a,\"的算术平方根=\",sqrtA( a ))\n",
    "\n",
    "\n",
    "a=2\n",
    "print( a,\"的算术平方根=\",sqrtA2( a ))\n",
    "a=3\n",
    "print( a,\"的算术平方根=\",sqrtA2( a ))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4b589587-dbbb-41f8-96e3-2af92987429e",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
